package com.top.horizon.th1804app.ui.fragment;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.net.protocol.NetController;
import com.net.protocol.model.RecordFile;
import com.top.horizon.th1804app.R;
import com.top.horizon.th1804app.base.BaseFragment;
import com.top.horizon.th1804app.manager.FileManage;
import com.top.horizon.th1804app.view.CustomDialog;
import com.top.horizon.th1804app.view.widget.DateChooseWheelViewDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.awt.font.TextAttribute;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileManagementFragment extends BaseFragment implements View.OnClickListener, CustomDialog.OnClickChildVIewListener {

    private EditText etSearch;
    private PopupWindow pullDownList;
    private Button btnSearch;
    private EditText etMinSize, etMaxSize;
    private TextView tvStartTime;
    private TextView tvOverTime;
    private EditText etTag;
    private int searchId;
    //0的时候，搜索框有内容按标签搜索，无内容按0搜索
    private final int SEARCH_TAG_NONE = 0;
    //按时间搜索
    private final int SEARCH_TAG_TIME = 1;
    //按大小搜索
    private final int SEARCH_TAG_SIZE = 2;

    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {

        }
    };
    private Button playList;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_file_management;
    }

    @Override
    protected void initView() {
        etSearch = rootView.findViewById(R.id.et_search);
        playList = rootView.findViewById(R.id.btn_play_list);
        //默认按无搜索
        etSearch.setTag(0);
        btnSearch = rootView.findViewById(R.id.btn_search);
        btnSearch.setOnClickListener(this);
        etSearch.setOnClickListener(this);
        playList.setOnClickListener(this);

    }


    @Override
    protected void initData() {
        //注册事件监听
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void searchEvent(List<RecordFile> files) {
        dismissProgressLoadingDialog();
        if (files == null || files.size() == 0) {
            showToast("没有搜索到文件");
            return;
        }
        //搜索到了文件，交给管理者，searchFragment就从管理者那里取文件
        FileManage.getInstance().setData(files);
        //调整到结果页面
        if (mOnClickSearchListener != null) {
            mOnClickSearchListener.onClickSearch(btnSearch);
        }

    }

    private SearchFragment.OnClickPlayBackListener mOnClickPlayBackListener;//2、定义接口成员变量

    //定义接口变量的set方法
    public void setOnClickPlayBackListener(SearchFragment.OnClickPlayBackListener onClickPlayBackListener) {
        this.mOnClickPlayBackListener = onClickPlayBackListener;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_play_list:
                if (FileManage.getInstance().getPlayDataSize() == 0) {
                    showToast("回放列表为空");
                    return;
                }
                FileManage.getInstance().isList =true;
                if (mOnClickPlayBackListener != null)
                    mOnClickPlayBackListener.onClickPlayBack();
                break;
            case R.id.et_search:
                //弹出下拉选项列表
                showPullDownListDialog();
                break;
            case R.id.tv_nothing_search:
                //选择无条件查询
                etSearch.setText("");
                etSearch.setHint("无条件搜索");
                pullDownList.dismiss();
                //请求数据
                searchId = NetController.search();
                break;
            case R.id.tv_time_search:
                //弹出选择按时间查询对话框
                showChooseDialog(R.layout.dialog_time_search);
//                showToast("选择按时间查询");
                pullDownList.dismiss();
                break;
            case R.id.tv_tag_search:
                //选择按标签查询
                showChooseDialog(R.layout.dialog_tag_search);
                pullDownList.dismiss();
                break;
            case R.id.tv_size_search:
                //选择按大小查询
                showChooseDialog(R.layout.dialog_size_search);
                pullDownList.dismiss();
                break;
            case R.id.btn_search:
                //搜索按钮点击事件
                handleSearch();
                break;
            case R.id.btn_confirm_time:
                etSearch.setTag(SEARCH_TAG_TIME);
                //点击按时间搜索对话框确认按钮，获取选择框的数据显示到对话框
                String startTime = tvStartTime.getText().toString().trim();
                String overTime = tvOverTime.getText().toString().trim();
                if (TextUtils.isEmpty(startTime) || TextUtils.isEmpty(overTime)){
                    showToast("请填写开始和结束时间");
                    return;
                }
                etSearch.setText((TextUtils.isEmpty(startTime) ? "" : startTime) + "&"
                        + (TextUtils.isEmpty(overTime) ? "" : overTime));
                dismissDialog();
                break;
            case R.id.tv_start_time:
                //点击按时间搜索对话框内的开始时间弹出对话框
                DateChooseWheelViewDialog startDateChooseDialog = new DateChooseWheelViewDialog(getContext(),
                        new DateChooseWheelViewDialog.DateChooseInterface() {
                            @Override
                            public void getDateTime(String time, boolean longTimeChecked) {
                                tvStartTime.setText(time);
                            }
                        });
                startDateChooseDialog.setDateDialogTitle("选择时间");
                startDateChooseDialog.showDateChooseDialog();
                break;
            case R.id.tv_over_time:
                //点击按时间搜索对话框确认按钮，获取选择框的数据显示到对话框
                DateChooseWheelViewDialog startDateChooseDialog1 = new DateChooseWheelViewDialog(getContext(),
                        new DateChooseWheelViewDialog.DateChooseInterface() {
                            @Override
                            public void getDateTime(String time, boolean longTimeChecked) {
                                tvOverTime.setText(time);
                            }
                        });
                startDateChooseDialog1.setDateDialogTitle("选择时间");
                startDateChooseDialog1.showDateChooseDialog();
                break;


            case R.id.btn_confirm_size:
                etSearch.setTag(SEARCH_TAG_SIZE);
                //点击按大小搜索对话框确认按钮，获取选择框的数据显示到对话框
                String minSize = etMinSize.getText().toString().trim();
                String maxSize = etMaxSize.getText().toString().trim();
                etSearch.setText((TextUtils.isEmpty(minSize) ? "" : minSize) + "&"
                        + (TextUtils.isEmpty(maxSize) ? "" : maxSize));
                dismissDialog();
                break;
            case R.id.btn_confirm_tag:
                //点击按标签搜索对话框确认按钮，获取选择框的数据显示到对话框
                String tag = etTag.getText().toString().trim();
                etSearch.setText(tag);
                dismissDialog();
                break;
            case R.id.btn_cancel:
                //点击对话框取消按钮
                dismissDialog();
                break;
        }
    }

    /**
     * 搜索按键监听
     */
    private void handleSearch() {
        int tag = (int) etSearch.getTag();
        switch (tag) {
            case SEARCH_TAG_TIME:
                //按时间搜索
                Editable text = etSearch.getText();
                if (text != null) {
                    String trim = text.toString().trim();
                    String[] split = trim.split("&");
                    if (split != null && split.length == 2) {
                        //调用网络接口
                        showProgressLoadingDialog();
                        searchId = NetController.searchTime(split[0], split[1]);
                    } else {
                        showToast("请输入正确的时间格式");
                    }
                } else {
                    showToast("请输入正确的时间格式");
                }
                break;
            case SEARCH_TAG_SIZE:
                //按大小搜索
                Editable textSize = etSearch.getText();
                if (textSize != null) {
                    String trim = textSize.toString().trim();
                    String[] split = trim.split("&");
                    if (split != null && split.length == 2) {
                        try {
                            int minSize = Integer.parseInt(split[0]);
                            int maxSize = Integer.parseInt(split[1]);
                            //调用网络接口
                            showProgressLoadingDialog();
                            searchId = NetController.searchSize(minSize, maxSize);
                        } catch (Exception e) {
                            showToast("请输入正确的大小格式");
                        }
                    } else {
                        showToast("请输入正确的大小格式");
                    }
                } else {
                    showToast("请输入正确的大小格式");
                }
                break;
            case SEARCH_TAG_NONE:

                Editable texttag = etSearch.getText();
                if (texttag != null && !TextUtils.isEmpty(texttag)) {
                    //按标签内容搜索
                    //调用网络接口
                    showProgressLoadingDialog();
                    searchId = NetController.searchTab(texttag.toString().split(" "));
                } else {
                    //无条件搜索
                    //调用网络接口
                    showProgressLoadingDialog();
                    searchId = NetController.search();
                }
                break;
        }
        //test begin
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                List<RecordFile> fiels = new ArrayList<>();
                for (int i = 0; i < 10; i++) {
                    RecordFile file = new RecordFile();
                    file.isSelected =false;
                    file.endTime = "2018-08-08 12:12:12";
                    file.startTime = "2018-08-08 12:12:12";
                    file.name = "name+"+i;
                    file.size = 1000;
                    fiels.add(file);
                }
                EventBus.getDefault().post(fiels);
            }
        },3_000);
        //test end
    }

    /**
     * 对话框内设置点击事件监听
     *
     * @param view
     * @param mLayoutId
     */
    @Override
    public void onClickChildView(View view, int mLayoutId) {
        switch (mLayoutId) {
            case R.layout.dialog_time_search:
                //按时间搜索对话框
                tvStartTime = view.findViewById(R.id.tv_start_time);
                tvOverTime = view.findViewById(R.id.tv_over_time);
                tvStartTime.setOnClickListener(this);
                tvOverTime.setOnClickListener(this);
                view.findViewById(R.id.btn_cancel).setOnClickListener(this);
                view.findViewById(R.id.btn_confirm_time).setOnClickListener(this);
                break;
            case R.layout.dialog_tag_search:
                //按标签搜索对话框
                etTag = view.findViewById(R.id.et_tag);
                setEditTextInputSpeChat(etTag);
                view.findViewById(R.id.btn_cancel).setOnClickListener(this);
                view.findViewById(R.id.btn_confirm_tag).setOnClickListener(this);
                break;
            case R.layout.dialog_size_search:
                //按大小搜索对话框
                etMinSize = view.findViewById(R.id.et_min_size);
                etMaxSize = view.findViewById(R.id.et_max_size);
                view.findViewById(R.id.btn_cancel).setOnClickListener(this);
                view.findViewById(R.id.btn_confirm_size).setOnClickListener(this);
                break;
        }
    }

    private OnClickSearchListener mOnClickSearchListener;//2、定义接口成员变量

    /**
     * 显示下拉列表对话框
     */
    private void showPullDownListDialog() {
        // 用于PopupWindow的View
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.pull_down_list, null, false);
        //给条目设置点击事件
        contentView.findViewById(R.id.tv_nothing_search).setOnClickListener(this);
        contentView.findViewById(R.id.tv_time_search).setOnClickListener(this);
        contentView.findViewById(R.id.tv_tag_search).setOnClickListener(this);
        contentView.findViewById(R.id.tv_size_search).setOnClickListener(this);
        // 创建PopupWindow对象，其中：
        // 第一个参数是用于PopupWindow中的View，第二个参数是PopupWindow的宽度，
        // 第三个参数是PopupWindow的高度，第四个参数指定PopupWindow能否获得焦点
        pullDownList = new PopupWindow(contentView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        // 设置PopupWindow的背景
        pullDownList.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // 设置PopupWindow是否能响应外部点击事件
        pullDownList.setOutsideTouchable(true);
        // 设置PopupWindow是否能响应点击事件
        pullDownList.setTouchable(true);
        // 显示PopupWindow，其中：
        // 第一个参数是PopupWindow的锚点，第二和第三个参数分别是PopupWindow相对锚点的x、y偏移
        pullDownList.showAsDropDown(etSearch, 0, 0);
    }

    //定义接口变量的set方法
    public void setOnClickSearchListener(OnClickSearchListener onClickSearchListener) {
        this.mOnClickSearchListener = onClickSearchListener;
    }

    //1、定义接口
    public interface OnClickSearchListener {
        void onClickSearch(View view);
    }

    @Override
    public void onPause() {
        super.onPause();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText EditText输入框
     */
    public static void setEditTextInputSpeChat(EditText editText) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (matcher.find()) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }
}
